//index.js
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectMember: true,
    creater: {},
    project_product_id: '',
    project_name: '',
    project_area: '',
    project_suit: '',
    project_update_date: '',
    project_update_person: '',
    project_id: '',
    category: '',
    product_area: 0,
    product_suit: 0,
    members: [],
    users: [],
    stages: [],
    index: 0,
    stage_id: 0,
    all_members: [],
    checkbox_users: [],
    leaderId: '',
    btndisabled: true,
    checkbox_members: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    //  let _that = this;
    //  app.getToken().then(function (){
    //    _that.loadData();
    //  });
    //},
    //
    //loadData: function (){

    const that = this;
    wx.showLoading({
      title: '加载中',
    });

    //所有成员
    wx.request({
      url: app.globalData.requestUrl + 'api/user/lists',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
      },
      success: function (ret) {
        let data = ret.data;
        //根据分类ID查询分类名称：
        var lists = data.data.lists;
        for (var i in lists) {
          var majorName = lists[i][0].major_info.major_name;
          lists[majorName] = lists[i];
          delete lists[i];
        };

        let linea_member = [];
        //全部成员转为二维  
        for (let key of Object.keys(lists)) {
          for (let index of lists[key]) {
            linea_member.push(index);

          }
        }
        wx.setStorageSync('members', linea_member);

      },
      fail: function (e) {
        wx.showLoading({
          title: '系统错误请稍后重试',
        });
      }
    })

    //获取成员列表

    wx.request({
      url: app.globalData.requestUrl + 'api/user/lists',
      method: 'POST',
      data: {
        id: app.globalData.userToken,
      },
      success: function (ret) {
        let data = ret.data;
        var lists = data.data.lists;


        // 根据分类ID查询分类名称：
        for (var i in lists) {
          var majorName = lists[i][0].major_info.major_name;
          lists[majorName] = lists[i];
          delete lists[i];
        };
        that.setData({
          all_members: lists,
        });
      },
      fail: function (e) {
        wx.showLoading({
          title: '系统错误请稍后重试',
        });
      }
    })

    //项目信息
    wx.request({
      url: app.globalData.requestUrl + 'api/project/detail',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
        project_id: options.project_id
      },
      success: function (res) {
        let area = 0,
          suit = 0,
          liner_member = wx.getStorageSync('members'),
          creater = {},
          category = {};
        //查询完整的创建人信息

        for (let value of liner_member) {

          if (value.id == res.data.data.project.create_member) {
            creater = value
          }

        }

        for (let value of res.data.data.project.products) {
          area += value.area;
          suit += value.tao;
          if (value.category_id == options.category_id) {
            category = value;
          }

        }
        that.setData({
          creater: creater,
          project_name: res.data.data.project.project_name,
          project_area: area,
          project_suit: suit,
          project_update_date: res.data.data.project.update_date,
          project_update_person: res.data.data.project.history[0].user.user_name,
          project_id: options.project_id,
          category: category,
          product_area: category.area,
          product_suit: category.tao,
        })

      }, fail: function () {

        wx.showToast({
          title: '系统错误请稍后重试',
          icon: 'none'
        });
      }
    });

    //阶段数据
    wx.request({
      url: app.globalData.requestUrl + 'api/stage/lists',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
      },
      success: function (res) {

        wx.setStorageSync('stages', res.data.data.lists);

      },
      fail: function (e) {
        wx.showLoading({
          title: '系统错误请稍后重试',
        });
      }
    })

    //产品详情

    wx.request({
      url: app.globalData.requestUrl + 'api/project/detail/product',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
        project_product_id: options.product_id
      },
      success: function (res) {
        wx.hideLoading();
        let member_ids = [],
          members = [],
          liner_member = wx.getStorageSync('members'),
          stages = wx.getStorageSync('stages');

        for (let value of res.data.data.product.members) {
          member_ids.push({ id: value.member_id, role: value.role });
        }

        for (let value of liner_member) {
          for (let item of member_ids) {
            if (value.id == item.id) {
              value.product_role = item.role;
              members.push(value);
            }
          }
        }
        //阶段index
        let temp_index = 0;
        for (let key of Object.keys(stages)) {

          if (stages[key].id == res.data.data.product.stage) {
            temp_index = key
          }
        }
        let member_temp = Array.from(new Set(members)).map((item) => {
          if (item.product_role == 9) {
            item.chosed = true;
          } else {
            item.chosed = false;
          }
          return item
        });

        let choseIndex = member_temp.findIndex(member => member.product_role == 9);

        let member_woca = member_temp.filter((item)=> {
          return item.product_role != 9?true:false;
        })
        member_woca.unshift(member_temp[choseIndex]);

        let member_wocale = member_woca.filter(mem=>{
          return mem == undefined?false:true;
        })

        console.log(member_wocale);

        that.setData({
          members: member_wocale,
          users: member_ids,
          checkbox_users: member_ids,
          checkbox_members: members,
          project_product_id: options.product_id,
          stages: stages,
          stage_id: res.data.data.product.stage,
          index: temp_index,
          leaderId: choseIndex == -1 ? '' : member_temp[choseIndex].id
        })
      },
      fail: function () {
        wx.showToast({
          title: '系统错误请稍后重试',
          icon: 'none'
        });
      }
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //临时修改面积
  updateProjectArea: function (e) {
    const that = this;
    let area = that.data.product_area;
    if (e.detail.value != "") {
      that.setData({
        product_area: e.detail.value.replace(/㎡/g, ""),
        btndisabled: e.detail.value.replace(/㎡/g, "") == area ? true : false
      })

    }
  },
  //临时修改套数
  updateProjectSuit: function (e) {
    const that = this;
    let tao = that.data.product_suit;
    if (e.detail.value != "") {

      that.setData({
        product_suit: e.detail.value.replace(/套/g, ""),
        btndisabled: e.detail.value.replace(/套/g, "") == tao ? true : false
      })
    }
  },
  //移除成员信息
  removeMember: function (e) {
    const that = this;
    let id = e.currentTarget.id;
    wx.showModal({
      content: '是否删除此成员',
      success: function (res) {
        if (res.confirm) {
          let users = that.data.users,
            members = that.data.members,
            temp_users = users.map((item)=> {
              if (item.id != id){
                return item;
              }
            });

          let use_members = temp_users.filter((item)=> {
            return !(!item || item === "");
          });

         let temp_memmber = members.filter(item=>{
              return item.id == id?false:true;
          })

          that.setData({
            users: use_members,
            members: temp_memmber,
            btndisabled: false
          })

        } else if (res.cancel) {
          wx.showToast({
            title: '删除取消',
            icon: 'none',
          });
        }
      }
    })
  },
  //修改阶段
  changStage: function (e) {
    const that = this;
    let stage_id = that.data.stage_id;
    this.setData({
      index: e.detail.value,
      stage_id: that.data.stages[e.detail.value]['id'],
      btndisabled: that.data.stages[e.detail.value]['id'] == stage_id ? true : false
    })
  },
  //添加成员
  addMember: function () {
    const that = this;
    let usersOBJ = that.data.users,//已添加用户的id 集合
      members = wx.getStorageSync('members'),//所有用户
      temp_members = [];
    let users = usersOBJ.map((item)=> {
      return item.id;
    })
    for (let key in members) {
      let obj = members[key];
      if (!that.contains(users, obj.id)) {
        temp_members.push(obj);
      }
    }
    let results = {};  //用于存储没有选择的用户
    for (var i in temp_members) {
      let majorName = temp_members[i].major_info.major_name;
      if (typeof results[majorName] != 'undefined' && results[majorName].length > 0) {
        results[majorName].push(temp_members[i]);  //当“某个专业”已经有用户，则push用户即可
      } else {
        results[majorName] = []; //如果没有“某个专业”的key,则创建一个空白数组
        results[majorName].push(temp_members[i]);
      }
    };
    that.setData({
      all_members: results,
      selectMember: false,
      btndisabled:true
    })
  },

  updateProduct: function () {
    const that = this;
    let product_id = that.data.project_product_id,
      category_id = that.data.category.category.id,
      stage = that.data.stage_id,
      area = that.data.product_area,
      tao = that.data.product_suit,
      leaderId = that.data.leaderId,
      btndisabled = that.data.btndisabled,
      users = that.data.users;

    if (btndisabled == true) {
      wx.showToast({
        title: '数据没有变动',
        icon: 'none'
      });
      return;
    }
    wx.showToast({
      title: '正在提交信息...',
      icon: 'none',
      duration: 200000
    });
    wx.request({
      url: app.globalData.requestUrl + 'api/project/edit/product',
      method: 'POST',
      data: {
        user_token: app.globalData.userToken,
        product_id: product_id,
        category_id: category_id,
        stage: stage,
        area: area,
        tao: tao,
        users: users,
        leaderId: leaderId
      },
      success: function (res) {
        wx.hideToast();
        if (res.data.status == 1) {
          wx.showToast({
            title: '修改成功',
            icon: 'none'
          });
          that.setData({
            btndisabled: true
          })
        }

      }, fail: function () {

        wx.showToast({
          title: '系统错误请稍后重试',
          icon: 'none'
        });
      }
    });
  },
  //复选框的的选择
  checkboxChange: function (e) {
    const that = this;
    let temp_users = that.data.checkbox_users,
      temp_members = that.data.checkbox_members,
      id = e.detail.value[0],
      storage_members = wx.getStorageSync('members');
    if (e.detail.value != false) {
      //     //勾选复选框
      if (!that.contains(temp_users, id)) {
        temp_users.push({id:id,role:0});
        for (let key of Object.keys(storage_members)) {
          let obj = storage_members[key];
          if (obj.id == parseInt(id)) {
            temp_members.push(obj)
          }
        }
        this.setData({
          checkbox_users: temp_users,
          checkbox_members: temp_members
        })
      }

    } else {
      //去掉勾选 
      let users = that.data.checkbox_users,
        members = that.data.checkbox_members,
        id = e.currentTarget.id;

      if (that.contains(users, id)) {

        users = app.removeValue(users, id);
        for (let key in members) {
          if (members[key].id == id) {
            members.splice(key);
          }
        }
        that.setData({
          checkbox_users: users,
          checkbox_members: members

        })
      }

    }
  },
  sureMember: function () {
    let users = this.data.checkbox_users,
      area = this.data.product_area,
      tao = this.data.product_suit,
      category = this.data.category,
      members = this.data.checkbox_members;
      category.area = area;
      category.tao = tao;
    this.setData({
      users: users,
      members: members,
      category: category,
      selectMember: true,
      btndisabled: false
    })

  },
  contains: function (arrObj, idObj) {
    let i = arrObj.length;
    while (i--) {
      if (parseInt(arrObj[i]) == idObj) {
        return true;
      }
    }
    return false;
  },
  cancelMember: function () {
    this.setData({
      selectMember: true
    })
  },
  call: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.id
    })
  },


  selectLeader: function (e) {
    const that = this;
    let leaderId = that.data.leaderId,
      members = that.data.members,
      choseId = e.currentTarget.id;

    let choseIndex = members.findIndex(member => member.id == e.currentTarget.id);

    let choseMember = members.find(member => member.id == e.currentTarget.id);

    members = members.map(item => {
      return item.chosed = false, item
    })

    choseMember.chosed = true;

    let member_woca = members.filter((item) => {
      return item.id != e.currentTarget.id ? true : false;
    })

    

    if (e.currentTarget.id == leaderId) {

      choseMember.chosed = false;
      choseId = '';
    }

    member_woca.unshift(choseMember);

    that.setData({
      members: member_woca,
      leaderId: choseId,
      btndisabled: choseId == leaderId?true:false
    })
  }


})